<?php

namespace App\Http\Controllers\Front;

use App\Http\Controllers\Controller;
use App\Model\Admin\Product;
use App\Model\Front\ShoppingCart;
use App\Services\UpdateQtyService;
use Gloudemans\Shoppingcart\Facades\Cart;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class CartController extends Controller
{
    protected $updateqtyService;

    public function __construct(UpdateQtyService $updateqtyService)
    {
        $this->updateqtyService = $updateqtyService;
    }


    public function index()
    {
        
        $carts = Cart::instance('shopping')->content();          
        return view('front.cart', compact('carts'))
               ->withCatcount(Cart::count())
               ->withSubtotal(Cart::subtotal());
    }

    public function create(Product $product)
    {
        
        Cart::instance('shopping')->add($product->pro_code, $product->pro_name, 1, $product->pro_prices, $product->pro_img, $product->pro_stock); 
        if (Auth::check()) 
        {
            Cart::instance('shopping')->add($product->pro_code, $product->pro_name, 1, $product->pro_prices, $product->pro_img, $product->pro_stock); 
            ShoppingCart::deleteCartRecord(Auth::user()->name,'shopping');
            Cart::store(Auth::user()->name);

        } 
        return back();
    }

    public function update($rowId, $qty=array())
    {
        $findCart = Cart::instance('shopping')->get($rowId);
        if (request()->qty > $findCart->stock) {
            return response()->json(['status'=>'maxqtx']);
        }
        $setUpdate = $this->updateqtyService->setQtyCount($rowId, request()->type, request()->qty, request()->stock);
        if(Auth::check()){
            $cart = Cart::instance('shopping')->content();

             ShoppingCart::where('identifier',Auth::user()->name)->update(['content'=>serialize($cart)]);
             
            

        }
        return $setUpdate;
    }

    public function destroy($rowId)
    {
        if(Auth::check()){

            Cart::instance('shopping')->remove($rowId);

        }else{
        
            Cart::instance('shopping')->remove($rowId);

        }
        return back();
    }

    public function clear()
    {
        Cart::instance('shopping')->destroy();
        return back();
    }
}
